package reflectCus;

import reflectCus.annotations.AutoRunClass;
import reflectCus.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;

//注解调用
public class Test6 {
    public static void main(String[] args) throws Exception {

        File f=new File(Test2.class.getResource(".").toURI());
        System.out.println(f);



        String packageName=Test2.class.getPackage().getName();
        String p=".class";

        String[] strings = f.list((o1,o2)->o2.endsWith(p));
        System.out.println(Arrays.toString(strings));
        for (String s:strings
        ) {
            if(s.endsWith(".class")){
                int lastIndex= s.lastIndexOf(".");
                String line=s.substring(0,lastIndex);

                Class cls=Class.forName(packageName+"."+line);
                if(cls.isAnnotationPresent(AutoRunClass.class)){
                    //=cls.getAnnotation(AutoRunClass.class)
                    System.out.println("被AutoRunClass标注："+cls.getName());
                    Object o=cls.newInstance();
                    Method[] methods=cls.getDeclaredMethods();
                    for (Method m:methods
                    ) {
                        // m.getModifiers()== Modifier.PRIVATE
                        if(m.isAnnotationPresent(AutoRunMethod.class) &&m.getParameterCount()==0 ){
                            System.out.println("被AutoRunMethod标注的方法执行"+m);
                            System.out.println(m.getDeclaringClass());
                            System.out.println(m.getGenericReturnType());
                            AutoRunMethod arm=m.getAnnotation(AutoRunMethod.class);
                            int times=arm.runTimes();
                            while (times>0){
                                m.setAccessible(true);
                                m.invoke(o);
                                times--;
                            }

                        }
                    }
                    System.out.println(o);
                }

            }
        }
    }
}
